import 'dart:typed_data';

import 'package:ble_helper_plugin/library.dart';
import 'package:bluetooth_protocols_parser_plugin/library.dart';
import 'package:bluetooth_protocols_parser_plugin_example/extension.dart';
import 'package:bluetooth_protocols_parser_plugin_example/loading.dart';
import 'package:bluetooth_protocols_parser_plugin_example/utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class HuariPage extends StatefulWidget {
  const HuariPage({super.key});

  @override
  State<HuariPage> createState() => _HuariPageState();
}

class _HuariPageState extends State<HuariPage> {
  final identifierBytes1 = Uint8List.fromList([
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x01
  ]);

  final identifierBytes2 = Uint8List.fromList([
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x03,
    0x01
  ]);

  final masterKey = Uint8List.fromList([0x11, 0x22, 0x33, 0x44]);

  // 协议类型
  final Protocol _protocol = CarKeyProtocol();

  // 随机码
  Uint8List randomCode = Uint8List(4);

  // 密钥列表
  List<int> pairedKeys = [];

  // 周期数据Map
  Rx<Map<String, dynamic>>? periodicDataMap = Rx<Map<String, dynamic>>({});

  //
  CustomScanResult? _result;

  @override
  void initState() {
    super.initState();
    // 监听蓝牙通知数据
    _protocol.listenBluetoothNotifyStream(callbackNfcCardPairSuccess: (p0) {
      // NFC卡是否配对成功
      debugPrint("NFC卡是否配对成功 = $p0");
      Loading.showToast("NFC卡是否配对成功 = $p0");
    }, callbackRealtimeInfo: (p0) {
      // 车辆实时数据
      periodicDataMap?.value = p0.toMap();
    });
  }

  @override
  Widget build(BuildContext context) {
    // 从 ModalRoute 中获取参数
    Map<String, CustomScanResult?> rsp = ModalRoute.of(context)
        ?.settings
        .arguments as Map<String, CustomScanResult?>;
    _result = rsp['result'];
    debugPrint("Received result: ${_result?.device.advName}");
    return Scaffold(
      appBar: AppBar(
        title: Text('${_result?.device.advName}'),
      ),
      body: Material(
        child: Container(
          padding: const EdgeInsets.all(8),
          width: double.infinity,
          height: double.infinity,
          color: Colors.grey[800],
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                ElevatedButton(
                  onPressed: () {
                    _startPressureTest().catchErrorHandler();
                  },
                  child: const Text('开始压测'),
                ),
                ElevatedButton(
                  onPressed: () {
                    _enablePeriodicDataSwitch(true).then((rsp) {
                      if (rsp) {
                        _showDialog();
                      } else {
                        Loading.showToast('开启周期数据失败');
                      }
                    });
                  },
                  child: const Text('查看周期数据'),
                ),
                _wrapWights([
                  ElevatedButton(
                    onPressed: () =>
                        _enablePeriodicDataSwitch(true).catchErrorHandler(),
                    child: const Text('开启周期数据'),
                  ),
                  ElevatedButton(
                    onPressed: () =>
                        _enablePeriodicDataSwitch(false).catchErrorHandler(),
                    child: const Text('关闭周期数据'),
                  ),
                  ElevatedButton(
                    onPressed: () => _getCurrentVehicleBindStatus(),
                    child: const Text(' 获取当前车辆认证状态'),
                  ),
                  ElevatedButton(
                    onPressed: () => _getRandomCode().catchErrorHandler(),
                    child: const Text('获取身份认证随机码'),
                  ),
                  Visibility(
                    visible: randomCode.isNotEmpty && randomCode.length == 4,
                    child: ElevatedButton(
                      onPressed: () =>
                          _verifyEncryptRandomNumber().catchErrorHandler(),
                      child: const Text('随机数校验'),
                    ),
                  ),
                  ElevatedButton(
                    onPressed: () => _addMasterKey().catchErrorHandler(),
                    child: Text('写入主钥匙:$masterKey'),
                  ),
                  ElevatedButton(
                    onPressed: () => _deleteMasterKey().catchErrorHandler(),
                    child: const Text('删除主密钥'),
                  ),
                  Visibility(
                    visible: randomCode.isNotEmpty && randomCode.length == 4,
                    child: ElevatedButton(
                      onPressed: () => _addSubKey().catchErrorHandler(),
                      child: const Text('写入子钥匙'),
                    ),
                  ),
                  ElevatedButton(
                    onPressed: () => _getKeyList().catchErrorHandler(),
                    child: const Text('获取密钥id列表'),
                  ),
                  ElevatedButton(
                    onPressed: () => _deleteSubKey().catchErrorHandler(),
                    child: const Text('删除子钥匙'),
                  ),
                  ElevatedButton(
                    onPressed: () => _protocol
                        .writeProductModel(Uint8List.fromList([
                      0x00,
                      0x01,
                      0x02,
                      0x03,
                      0x04,
                      0x05,
                      0x06,
                      0x07,
                      0x08,
                      0x09,
                      0x0A,
                      0x0B,
                      0x0C,
                      0x0D,
                      0x0E,
                      0x0F
                    ]))
                        .then((rsp) {
                      Loading.showToast(
                          '写入产品型号: ${rsp.isSuccess ? "成功" : "失败"}');
                    }).catchErrorHandler(),
                    child: const Text('写入产品型号[0x01, 0x02, 0x03, 0x04]'),
                  ),
                  ElevatedButton(
                    onPressed: () => _protocol.getProductModel().then((rsp) {
                      if (rsp.isSuccess) {
                        Loading.showToast('获取产品型号: ${rsp.data}');
                      } else {
                        Loading.showToast('获取产品型号失败');
                      }
                    }).catchErrorHandler(),
                    child: const Text('获取产品型号'),
                  ),
                  ElevatedButton(
                    onPressed: () => _protocol.getSn().then((rsp) {
                      if (rsp.isSuccess) {
                        Loading.showToast('SN: ${rsp.data}');
                      } else {
                        Loading.showToast('获取SN失败');
                      }
                    }).catchErrorHandler(),
                    child: const Text('获取SN'),
                  ),
                  ElevatedButton(
                    onPressed: () => _writeActiveTime().catchErrorHandler(),
                    child: const Text('写入激活时间'),
                  ),
                  ElevatedButton(
                    onPressed: () => _lock().catchErrorHandler(),
                    child: const Text('锁车'),
                  ),
                  ElevatedButton(
                    onPressed: () => _unLock().catchErrorHandler(),
                    child: const Text('解锁'),
                  ),
                  ElevatedButton(
                    onPressed: () => _enterNfcCardMode().catchErrorHandler(),
                    child: const Text('进入配卡模式'),
                  ),
                  ElevatedButton(
                    onPressed: () => _exitNfcCardMode().catchErrorHandler(),
                    child: const Text('退出配卡模式'),
                  ),
                  ElevatedButton(
                    onPressed: () => _deleteNfcCard().catchErrorHandler(),
                    child: const Text('删除卡片'),
                  ),
                  ElevatedButton(
                    onPressed: () => _setMotorControllerCurve(
                      Uint8List.fromList([0x00, 0x90]),
                      Uint8List.fromList([0x00, 0x01]),
                    ).catchErrorHandler(),
                    child: const Text('设置TRAIL档刹车断电: true'),
                  ),
                  ElevatedButton(
                    onPressed: () => _setMotorControllerCurve(
                      Uint8List.fromList([0x00, 0x90]),
                      Uint8List.fromList([0x00, 0x00]),
                    ).catchErrorHandler(),
                    child: const Text('设置TRAIL档刹车断电: false'),
                  ),
                  ElevatedButton(
                    onPressed: () =>
                        _getControllerData(Uint8List.fromList([0x00, 0x90]))
                            .catchErrorHandler(),
                    child: const Text('获取TRAIL档刹车断电状态'),
                  ),
                ]),
              ],
            ),
          ),
        ),
      ),
    );
  }

  _wrapWights(List<Widget> widgetList) {
    return Column(
      children: [
        const SizedBox(height: 10),
        Wrap(
          spacing: 8,
          runSpacing: 4,
          alignment: WrapAlignment.start,
          children: widgetList,
        ),
      ],
    );
  }

  // 获取当前车辆是否已经绑定的状态
  _getCurrentVehicleBindStatus() {
    Loading.showLoading(null);
    // 这里可以调用协议方法获取车辆绑定状态
    return _protocol.getAuthRandomCode(identifierBytes1).then((rsp) {
      switch (rsp.code) {
        case 0x00:
          Loading.showToast('获取当前车辆认证状态：失败');
        case 0x01:
          Loading.showToast('获取当前车辆认证状态：未认证');
        case 0x02:
          Loading.showToast('获取当前车辆认证状态：已认证');
        case 0x03:
          Loading.showToast('获取当前车辆认证状态：认证车辆到达上限');
        default:
          Loading.showToast('获取当前车辆认证状态: 未知错误code=${rsp.code}');
      }
    }).catchErrorHandler();
  }

  // 获取身份认证随机码
  Future<bool> _getRandomCode() async {
    return _protocol.getAuthRandomCode(identifierBytes1).then((rsp) {
      if (rsp.isSuccess && rsp.data.length == 4) {
        randomCode = rsp.data;
        Loading.showToast("取身份认证随机码: $randomCode");
        return Future(() => true);
      } else {
        Loading.showToast("获取身份认证随机码失败");
        return Future(() => false);
      }
    });
  }

  // 验证加密随机数
  Future<bool> _verifyEncryptRandomNumber() {
    if (randomCode.isEmpty || randomCode.length != 4) {
      Loading.showToast("请先获取身份认证随机码");
      return Future(() => false);
    }
    return _protocol.verifyEncryptRandomNumber(randomCode).then((rsp) {
      Loading.showToast('验证加密随机数: ${rsp.isSuccess ? "成功" : "失败"}');
      return Future(() => rsp.isSuccess);
    });
  }

  // 写入主密钥
  Future<bool> _addMasterKey() {
    return _protocol.addMasterKey(identifierBytes1, masterKey).then((rsp) {
      Loading.showToast('写入主密钥: ${rsp.isSuccess ? "成功" : "失败"}');
      return Future(() => rsp.isSuccess);
    });
  }

  // 删除主密钥
  Future<bool> _deleteMasterKey() {
    return _protocol.deleteMasterKey().then((rsp) {
      Loading.showToast('删除主密钥: ${rsp.isSuccess ? "成功" : "失败"}');
      return Future(() => rsp.isSuccess);
    });
  }

  // 写入副钥匙
  Future<bool> _addSubKey() {
    if (randomCode.isEmpty || randomCode.length != 4) {
      Loading.showToast('请先获取身份认证随机码');
      return Future(() => false);
    }
    return _protocol
        .addSubKey(identifierBytes2, randomCode, masterKey)
        .then((rsp) {
      Loading.showToast('写入副钥匙: ${rsp.isSuccess ? "成功" : "失败"}');
      return Future(() => rsp.isSuccess);
    });
  }

  // 获取密钥id列表
  Future<bool> _getKeyList() {
    return _protocol.getKeyList().then((rsp) {
      if (rsp.isSuccess) {
        if (rsp.data.isNotEmpty) {
          Loading.showToast('已配对的钥匙: ${rsp.data.toList()}');
          pairedKeys = rsp.data.toList();
          return Future(() => true);
        } else {
          Loading.showToast('没有已配对的钥匙');
          return Future(() => false);
        }
      } else {
        Loading.showToast('获取密钥id列表失败');
        return Future(() => false);
      }
    });
  }

  // 删除子钥匙
  Future<bool> _deleteSubKey() {
    // pairedKeys取16个字节或者16字节的倍数为一个key
    const int keyLength = 16;
    if (pairedKeys.isEmpty) {
      Loading.showToast('没有已配对的钥匙');
      return Future(() => false);
    }
    if (pairedKeys.length % keyLength != 0) {
      Loading.showToast('配对钥匙长度不正确,请检查');
      return Future(() => false);
    }
    if (pairedKeys.length <= keyLength) {
      Loading.showToast('没有可删除的子钥匙,主钥匙不可以通过这个接口删除');
      return Future(() => false);
    }
    // 删除第一个子钥匙
    Uint8List identifierBytes =
        Uint8List.fromList(pairedKeys.sublist(keyLength, keyLength * 2));
    // 这里需要传入要删除的钥匙identifierBytes，假设我们删除第一个子钥匙
    return _protocol.deleteSubKey(identifierBytes).then((rsp) {
      Loading.showToast('删除子钥匙: ${rsp.isSuccess ? "成功" : "失败"}');
      if (rsp.isSuccess) {
        pairedKeys.removeAt(0);
      }
      return Future(() => rsp.isSuccess);
    });
  }

  // 获取SN
  Future<bool> _getSN() {
    return _protocol.getSn().then((rsp) {
      Loading.showToast('SN: ${rsp.data2Text}');
      return Future(() => rsp.data2Text.isNotEmpty);
    });
  }

  // 锁车
  Future<bool> _lock() {
    return _protocol.lock(identifierBytes1).then((rsp) {
      Loading.showToast('锁车: ${rsp.isSuccess ? "成功" : "失败"}');
      return Future(() => rsp.isSuccess);
    });
  }

  // 解锁
  Future<bool> _unLock() {
    return _protocol.lock(identifierBytes1, false).then((rsp) {
      Loading.showToast('解锁: ${rsp.isSuccess ? "成功" : "失败"}');
      return Future(() => rsp.isSuccess);
    });
  }

  // 进入配卡模式
  Future<bool> _enterNfcCardMode() {
    return _protocol.enterNfcCardMode().then((rsp) {
      Loading.showToast('进入配卡模式: ${rsp.isSuccess ? "成功" : "失败"}');
      return Future(() => rsp.isSuccess);
    });
  }

  // 退出配卡模式
  Future<bool> _exitNfcCardMode() {
    return _protocol.exitNfcCardMode().then((rsp) {
      Loading.showToast('退出配卡模式: ${rsp.isSuccess ? "成功" : "失败"}');
      return Future(() => rsp.isSuccess);
    });
  }

  // 删除NFC卡
  Future<bool> _deleteNfcCard() {
    return _protocol
        .enterNfcCardMode()
        .then((value) => _protocol.deleteNfcCard())
        .then((value) => _protocol.exitNfcCardMode())
        .then((rsp) {
      Loading.showToast('删除NFC卡: ${rsp.isSuccess ? "成功" : "失败"}');
      return Future(() => rsp.isSuccess);
    });
  }

  // 写入激活时间
  Future<bool> _writeActiveTime() {
    return _protocol
        .writeActiveTime(Utils.int32ToBytes(Utils.getSecondStamp()))
        .then((success) {
      Loading.showToast('写入激活时间: ${success ? "成功" : "失败"}');
      return Future(() => success);
    });
  }

  // 开启周期数据开关
  Future<bool> _enablePeriodicDataSwitch(bool enable) {
    return _protocol.enablePeriodicDataSwitch(enable).then((success) {
      Loading.showToast(
          '周期数据开关${enable ? "开启" : "关闭"}: ${success ? "成功" : "失败"}');
      return Future(() => success);
    });
  }

  // 获取控制器曲线
  Future<bool> _getControllerData(Uint8List addrBytes) {
    return _protocol.getControllerData(addrBytes).then((rsp) {
      if (rsp.isSuccess) {
        Loading.showToast('RAIL档刹车断电: ${rsp.data.first.isOne}');
        return Future(() => true);
      } else {
        Loading.showToast('获取TRAIL档刹车断电失败');
        return Future(() => false);
      }
    });
  }

  // 设置控制器曲线
  Future<bool> _setMotorControllerCurve(
      Uint8List addrBytes, Uint8List dataBytes) {
    return _protocol.setControllerData(addrBytes, dataBytes).then((rsp) {
      Loading.showToast('设置TRAIL档刹车断电: ${rsp.isSuccess ? "成功" : "失败"}');
      return Future(() => rsp.isSuccess);
    });
  }

  // 显示Dialog
  void _showDialog() {
    if (periodicDataMap == null) {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('提示'),
            content: const Text('暂无周期数据'),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: const Text('确定'),
              ),
            ],
          );
        },
      );
    } else {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('周期数据'),
            content: Obx(() {
              return SingleChildScrollView(
                child: Column(
                  children: [
                    _currentMode(),
                    _speed(),
                    _odometer(),
                    _mcuTemperature(),
                    _motorTemperature(),
                    _motorTorque(),
                    _motorPower(),
                    _bmsSoc(),
                    _bmsSoh(),
                    _bmsTemperature(),
                    _currentMeter(),
                    _bmsErrorShortCircuit(),
                    _bmsErrorGroupOverVoltage(),
                    _bmsErrorGroupLowVoltage(),
                    _bmsErrorMosOverTemp(),
                    _bmsErrorDischargeOverTemp(),
                    _bmsErrorDischargeOverCurrent(),
                    _bmsErrorDischargeMosDefect(),
                    _mcuPhaseCurrentOver(),
                    _mcuBusbarVoltHigh(),
                    _mcuBusbarVoltLow(),
                    _mcuLogicVoltLow(),
                    _mcuLogicVoltHigh(),
                    _lockStatus(),
                  ],
                ),
              );
            }),
          );
        },
      );
    }
  }

  /*
    speed: 0, odometer: 0, mcuTemperature: 0, motorTemperature: 0, motorTorque: 0, motorPower: 0, bmsSoc: 0, bmsSoh: 0, bmsTemperature: 0, currentMeter: 0.0, currentMode: 0, bmsErrorShortCircuit: false, bmsErrorGroupOverVoltage: false, bmsErrorGroupLowVoltage: false, bmsErrorMosOverTemp: false, bmsErrorDischargeOverTemp: false, bmsErrorDischargeOverCurrent: false, bmsErrorDischargeMosDefect: false, mcuPhaseCurrentOver: false, mcuBusbarVoltHigh: false, mcuBusbarVoltLow: false, mcuLogicVoltLow: false, mcuLogicVoltHigh: false, lockStatus: true
  */

  // 当前速度
  _speed() {
    return Row(
      children: [
        const Text('当前速度：'),
        Text('${periodicDataMap!.value["speed"]} km/h'),
      ],
    );
  }

  // 总里程
  _odometer() {
    return Row(
      children: [
        const Text('总里程：'),
        Text('${periodicDataMap!.value["odometer"]} km/h'),
      ],
    );
  }

  // mcuTemperature
  _mcuTemperature() {
    return Row(
      children: [
        const Text('MCU温度：'),
        Text('${periodicDataMap!.value["mcuTemperature"]} °C'),
      ],
    );
  }

  // motorTemperature
  _motorTemperature() {
    return Row(
      children: [
        const Text('电机温度：'),
        Text('${periodicDataMap!.value["motorTemperature"]} °C'),
      ],
    );
  }

  _motorTorque() {
    return Row(
      children: [
        const Text('电机扭矩：'),
        Text('${periodicDataMap!.value["motorTorque"]} Nm'),
      ],
    );
  }

  _motorPower() {
    return Row(
      children: [
        const Text('电机功率：'),
        Text('${periodicDataMap!.value["motorPower"]} W'),
      ],
    );
  }

  _bmsSoc() {
    return Row(
      children: [
        const Text('BMS SOC：'),
        Text('${periodicDataMap!.value["bmsSoc"]} %'),
      ],
    );
  }

  _bmsSoh() {
    return Row(
      children: [
        const Text('BMS SOH：'),
        Text('${periodicDataMap!.value["bmsSoh"]} %'),
      ],
    );
  }

  _bmsTemperature() {
    return Row(
      children: [
        const Text('BMS 温度：'),
        Text('${periodicDataMap!.value["bmsTemperature"]} °C'),
      ],
    );
  }

  // 当前里程
  _currentMeter() {
    return Row(
      children: [
        const Text('当前里程：'),
        Text('${periodicDataMap!.value["currentMeter"]} km'),
      ],
    );
  }

  _bmsErrorShortCircuit() {
    return Row(
      children: [
        const Text('BMS 短路故障：'),
        Text('${periodicDataMap!.value["bmsErrorShortCircuit"]}'),
      ],
    );
  }

  _bmsErrorGroupOverVoltage() {
    return Row(
      children: [
        const Text('BMS 电压过高故障：'),
        Text('${periodicDataMap!.value["bmsErrorGroupOverVoltage"]}'),
      ],
    );
  }

  _bmsErrorGroupLowVoltage() {
    return Row(
      children: [
        const Text('BMS 电压过低故障：'),
        Text('${periodicDataMap!.value["bmsErrorGroupLowVoltage"]}'),
      ],
    );
  }

  _bmsErrorMosOverTemp() {
    return Row(
      children: [
        const Text('BMS MOS 温度过高故障：'),
        Text('${periodicDataMap!.value["bmsErrorMosOverTemp"]}'),
      ],
    );
  }

  _bmsErrorDischargeOverTemp() {
    return Row(
      children: [
        const Text('BMS 放电温度过高故障：'),
        Text('${periodicDataMap!.value["bmsErrorDischargeOverTemp"]}'),
      ],
    );
  }

  _bmsErrorDischargeOverCurrent() {
    return Row(
      children: [
        const Text('BMS 放电过流故障：'),
        Text('${periodicDataMap!.value["bmsErrorDischargeOverCurrent"]}'),
      ],
    );
  }

  _bmsErrorDischargeMosDefect() {
    return Row(
      children: [
        const Text('BMS 放电MOS缺陷故障：'),
        Text('${periodicDataMap!.value["bmsErrorDischargeMosDefect"]}'),
      ],
    );
  }

  _mcuPhaseCurrentOver() {
    return Row(
      children: [
        const Text('MCU 相电流过高故障：'),
        Text('${periodicDataMap!.value["mcuPhaseCurrentOver"]}'),
      ],
    );
  }

  _mcuBusbarVoltHigh() {
    return Row(
      children: [
        const Text('MCU 母线电压高故障：'),
        Text('${periodicDataMap!.value["mcuBusbarVoltHigh"]}'),
      ],
    );
  }

  _mcuBusbarVoltLow() {
    return Row(
      children: [
        const Text('MCU 母线电压低故障：'),
        Text('${periodicDataMap!.value["mcuBusbarVoltLow"]}'),
      ],
    );
  }

  _mcuLogicVoltLow() {
    return Row(
      children: [
        const Text('MCU 逻辑电压低故障：'),
        Text('${periodicDataMap!.value["mcuLogicVoltLow"]}'),
      ],
    );
  }

  _mcuLogicVoltHigh() {
    return Row(
      children: [
        const Text('MCU 逻辑电压高故障：'),
        Text('${periodicDataMap!.value["mcuLogicVoltHigh"]}'),
      ],
    );
  }

  _lockStatus() {
    return Row(
      children: [
        const Text('锁车状态：'),
        Text(periodicDataMap!.value["lockStatus"] ? '已锁车' : '未锁车'),
      ],
    );
  }

  _currentMode() {
    String modeText = '未知';
    int mode = periodicDataMap!.value["currentMode"] ?? 0;
    switch (mode) {
      case 0:
        modeText = 'ECO模式';
        break;
      case 1:
        modeText = 'TRAIL模式';
        break;
      case 2:
        modeText = 'SPORT模式';
        break;
    }

    return Row(
      children: [
        const Text('当前模式：'),
        Text(modeText),
      ],
    );
  }

  // 开始压力测试
  Future<bool> _startPressureTest() {
    return _writeMasterKeyTesting().then((rsp1) {
      if (rsp1) {
        return _writeSubKeyTesting();
      }
      throw Exception("压力测试异常退出 - 主密钥写入失败");
    }).then((rsp2) {
      if (rsp2) {
        return _startPressureTest();
      }
      throw Exception("压力测试异常退出 - 副密钥写入失败");
    });
  }

  // 写入主密钥
  Future<bool> _writeMasterKeyTesting() {
    _showTestLoading();
    return _protocol.deleteMasterKey().then((rsp0) {
      return _protocol.getAuthRandomCode(identifierBytes1);
    }).then((rsp1) {
      return _protocol.verifyEncryptRandomNumber(rsp1.data);
    }).then((rsp2) {
      return _protocol.addMasterKey(identifierBytes1, masterKey);
    }).then((rsp3) {
      _showTestLoading();
      return _protocol.getKeyList();
    }).then((rsp4) {
      return rsp4.isSuccess;
    });
  }

  // 写入副密钥
  Future<bool> _writeSubKeyTesting() {
    _showTestLoading();
    return _protocol.getAuthRandomCode(identifierBytes2).then((rsp1) {
      return _protocol.verifyEncryptRandomNumber(rsp1.data);
    }).then((rsp2) {
      return _protocol.addSubKey(identifierBytes2, randomCode, masterKey);
    }).then((rsp3) {
      _showTestLoading();
      return _protocol.getKeyList();
    }).then((rsp4) {
      return rsp4.isSuccess;
    });
  }

  @override
  void dispose() {
    // 清理资源
    super.dispose();
  }

  _showTestLoading() {
    if (!Loading.isShow()) {
      Loading.showLoading("正在压力测试...\n退出请杀掉App进程");
    }
  }
}
